<template>
  <div class="api-manage-container">
    <div class="toolbar">
      <el-button type="primary" @click="handleCreateApi">
        <el-icon><Plus /></el-icon>新建接口
      </el-button>
      <el-input
        v-model="searchQuery"
        placeholder="搜索接口名称或路径"
        class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-table :data="apiList" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="接口名称" min-width="150" />
      <el-table-column prop="path" label="请求路径" min-width="150" />
      <el-table-column prop="method" label="请求方法" width="100" />
      <el-table-column prop="type" label="接口类型" width="120">
        <template #default="{ row }">
          <el-tag
            :type="row.type === ApiType.DataSource ? 'success' : 'warning'"
          >
            {{ getApiTypeLabel(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === ApiStatus.Enabled ? 'success' : 'info'">
            {{ row.status === ApiStatus.Enabled ? "启用" : "禁用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button-group>
            <el-button
              type="primary"
              link
              :loading="row.testing"
              @click="handleTest(row)"
            >
              测试
            </el-button>
            <el-button type="primary" link @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <ApiForm
      v-model:visible="formVisible"
      :loading="submitting"
      :editing-data="editingData"
      :api-type="selectedApiType"
      :dataSources="dataSourceList"
      :loadingDataSources="loadingDataSources"
      @submit="handleFormSubmit"
    />

    <ApiTypeSelect
      v-model:visible="typeSelectVisible"
      @select="handleTypeSelect"
      @openSqlEditor="handleOpenSqlEditor"
    />

    <SqlEditor
      v-model:visible="sqlEditorVisible"
      :apiData="editingData"
      @confirm="handleSqlConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from "vue";
import { Plus, Search } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import ApiForm from "./components/ApiForm.vue";
import ApiTypeSelect from "./components/ApiTypeSelect.vue";
import SqlEditor from "./components/SqlEditor.vue";
import {
  getApiList,
  createApi,
  updateApi,
  deleteApi,
  testApi,
} from "@/api/apiManage";
import { getDataSourceList } from "@/api/dataSource";
import type { ApiConfig } from "@/types/api";
import { ApiStatus, ApiType } from "@/types/api";
import type { DataSource } from "@/types/dataSource";

const loading = ref(false);
const searchQuery = ref("");
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const formVisible = ref(false);
const typeSelectVisible = ref(false);
const editingData = ref<ApiConfig | null>(null);
const selectedApiType = ref<ApiType>();
const apiList = ref<ApiConfig[]>([]);
const sqlEditorVisible = ref(false);
const dataSourceList = ref<DataSource[]>([]);
const loadingDataSources = ref(false);
const submitting = ref(false);

const getApiTypeLabel = (type: ApiType) => {
  const labels: Record<ApiType, string> = {
    [ApiType.DataSource]: "数据源接口",
    [ApiType.REST]: "REST接口",
  };
  return labels[type];
};

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      keyword: searchQuery.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    };
    const { list, total: totalCount } = await getApiList(params);
    apiList.value = list;
    total.value = totalCount;
  } catch (error) {
    console.error("加载API列表失败:", error);
  } finally {
    loading.value = false;
  }
};

const loadDataSources = async () => {
  console.log("开始加载数据源列表...");
  loadingDataSources.value = true;

  try {
    const result = await getDataSourceList({ page: 1, pageSize: 100 });
    console.log("数据源API返回结果:", result);

    if (result?.data?.data?.list) {
      dataSourceList.value = result.data.data.list;
      console.log("成功加载数据源, 数量:", dataSourceList.value.length);
    } else {
      console.error("API返回的数据结构不符合预期:", result);
      dataSourceList.value = [];
    }
  } catch (error) {
    console.error("加载数据源时发生错误:", error);
    dataSourceList.value = [];
  } finally {
    loadingDataSources.value = false;
  }
};

const handleCreateApi = () => {
  typeSelectVisible.value = true;
};

const handleTypeSelect = (type: ApiType) => {
  console.log("选择API类型:", type);
  selectedApiType.value = type;
  editingData.value = null;

  if (type === ApiType.DataSource) {
    handleOpenSqlEditor();
  } else {
    handleOpenForm();
  }
};

const handleEdit = (row: ApiConfig) => {
  editingData.value = { ...row };
  selectedApiType.value = row.type;

  if (row.type === ApiType.DataSource) {
    loadDataSources().then(() => {
      handleOpenSqlEditor(row);
    });
  } else {
    handleOpenForm(row);
  }
};

const handleTest = async (row: ApiConfig) => {
  if (!row.id) return;

  row.testing = true;
  try {
    const result = await testApi(row.id);
    if (result.success) {
      ElMessage.success(result.message);
    } else {
      ElMessage.error(result.message);
    }
  } catch (error) {
    ElMessage.error("测试失败");
  } finally {
    row.testing = false;
  }
};

const handleDelete = (row: ApiConfig) => {
  if (!row.id) return;

  ElMessageBox.confirm("确定要删除该接口吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    loading.value = true;
    try {
      await deleteApi(row.id);
      ElMessage.success("删除成功");
      loadData();
    } finally {
      loading.value = false;
    }
  });
};

const handleError = (error: any, context: string) => {
  console.error(`API管理 - ${context} 错误:`, error);
  ElMessage.error(`操作失败: ${error.message || "未知错误"}`);
};

const handleFormSubmit = async (data: ApiConfig) => {
  console.log("提交API表单数据:", data);
  console.log("当前可用数据源:", dataSourceList.value);

  if (!data.type) {
    ElMessage.warning("请选择接口类型");
    return;
  }

  if (data.type === ApiType.DataSource && !data.dataSourceId) {
    ElMessage.warning("请选择数据源");
    return;
  }

  submitting.value = true;
  try {
    if (data.id) {
      await updateApi(data.id, data);
      ElMessage.success("更新成功");
    } else {
      await createApi(data);
      ElMessage.success("创建成功");
    }
    loadData();
  } catch (error) {
    handleError(error, "提交表单");
  } finally {
    submitting.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  loadData();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  loadData();
};

const handleOpenSqlEditor = (apiData?: ApiConfig) => {
  console.log("打开SQL编辑器，API数据:", apiData);

  if (apiData) {
    editingData.value = apiData;
  }

  sqlEditorVisible.value = true;
};

const handleSqlConfirm = (sqlConfig: any) => {
  console.log("SQL已确认:", sqlConfig);

  if (!sqlConfig.dataSourceId) {
    ElMessage.warning("请选择数据源");
    return;
  }

  if (editingData.value) {
    editingData.value.config = {
      ...(editingData.value.config || {}),
      ...sqlConfig,
    };

    editingData.value.dataSourceId = sqlConfig.dataSourceId;

    formVisible.value = true;
  } else {
    const newApi: Partial<ApiConfig> = {
      type: ApiType.DataSource,
      dataSourceId: sqlConfig.dataSourceId,
      config: sqlConfig,
    };

    editingData.value = newApi as ApiConfig;
    formVisible.value = true;
  }
};

const handleOpenForm = async (api = null) => {
  console.log("打开表单, API:", api, "类型:", selectedApiType.value);
  editingData.value = api;

  if (!api || api.type === ApiType.DataSource) {
    await loadDataSources();
  }

  formVisible.value = true;
};

watch([searchQuery], () => {
  currentPage.value = 1;
  loadData();
});

onMounted(() => {
  loadData();
  loadDataSources();

  // 监听数据源变更事件
  window.addEventListener("datasource-changed", loadDataSources);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener("datasource-changed", loadDataSources);
});
</script>

<style scoped>
.api-manage-container {
  padding: 20px;
}

.toolbar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 300px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 